<template>
  <ConfirmModal
    :title="titleFinal"
    :show="show"
    :onConfirm="onConfirm"
    :onCancel="onCancel"
    useLoading
    :width="modalWidth"
    @update:show="onShow"
  >
    <FormMain
      ref="formMain"
      :list="list"
      :data="assertData"
      :layout="formLayout"
      :labelWidth="labelWidth"
      v-bind="formProps"
    >
    </FormMain>
  </ConfirmModal>
</template>

<script
  lang="ts"
  setup
  generic="PO extends Record<string, any>, SO extends Record<string, any>"
>
import type {
  FormMainInstance,
  ExtractFormStringifyFromObject,
} from "@/components/form";
import { stringifyFormData } from "@/components/form";
import type { DetailModalProps } from "./types";

const props = withDefaults(defineProps<DetailModalProps<PO, SO>>(), {
  modalWidth: 600,
  formLayout: () => ({ span: 24 }),
});

const emits = defineEmits<{
  (e: "update:show", value: boolean): void;
  (
    e: "afterAdd" | "afterEdit",
    data: ExtractFormStringifyFromObject<PO, SO>,
  ): void;
}>();

const labelWidth = "80px";

const formMain = ref<FormMainInstance>();

const assertData = computed(() => {
  return props.data as PO;
});

const titleFinal = computed(() => {
  return `${props.type === "add" ? "新增" : "编辑"}${props.subTitle || ""}`;
});

const onShow = (value: boolean) => {
  emits("update:show", value);
};

const onConfirm = () => {
  return formMain.value?.validate().then(async () => {
    const stringifyData = stringifyFormData(props.data, props.list);
    console.log("confirm", stringifyData);

    if (props.type === "add") {
      await props.addApi?.(stringifyData);
      emits("afterAdd", stringifyData);
    } else {
      await props.editApi?.(stringifyData);
      emits("afterEdit", stringifyData);
    }
  });
};

const onCancel = () => {
  console.log("cancel");
};

watch(
  () => props.show,
  (n) => {
    if (!n) {
      formMain.value?.clearValidate();
    }
  },
);
</script>
